package xyz.hubery.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import xyz.hubery.enums.CodeEnum;
import xyz.hubery.mapper.SeckillGoodsMapper;
import xyz.hubery.model.BusException;
import xyz.hubery.model.Constants;
import xyz.hubery.pojo.SeckillGoods;
import xyz.hubery.pojo.StockRecord;
import xyz.hubery.service.SeckillGoodsService;

import java.util.Date;

@DubboService
@Transactional
public class SeckillGoodsServiceImpl implements SeckillGoodsService {

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void add(SeckillGoods seckillGoods) {
        seckillGoodsMapper.insert(seckillGoods);
    }

    @Override
    public void update(SeckillGoods seckillGoods) {
        // 检查当前商品是否处于秒杀中（秒杀前5分钟内不允许修改）
        checkSeckillGoods(seckillGoods.getId());
        // 获取当前版本号
        SeckillGoods sqlSeckillGoods = seckillGoodsMapper.selectById(seckillGoods.getId());
        Integer oldVersion = sqlSeckillGoods.getVersion();
        // 带版本号的更新操作
        int i = seckillGoodsMapper.update(new UpdateWrapper<SeckillGoods>()
                .eq("id", seckillGoods.getId())
                .eq("version", oldVersion)
                .set("version", oldVersion + 1)
                .set("goodsId", seckillGoods.getGoodsId())
                .set("title", seckillGoods.getTitle())
                .set("introduction", seckillGoods.getIntroduction())
                .set("headerPic", seckillGoods.getHeaderPic())
                .set("price", seckillGoods.getPrice())
                .set("costPrice", seckillGoods.getCostPrice())
                .set("startTime", seckillGoods.getStartTime())
                .set("endTime", seckillGoods.getEndTime())
                .set("num", seckillGoods.getNum())
                .set("stockCount", seckillGoods.getStockCount())
        );
        if(i > 0) { // 说明操作成功，记录一条库存操作记录
            StockRecord stockRecord = new StockRecord();
            stockRecord.setGoodsId(sqlSeckillGoods.getGoodsId());
            stockRecord.setChangeQuantity(seckillGoods.getNum());
            stockRecord.setOperationType(3);
            stockRecord.setOperationTime(new Date());
            stockRecord.setOperator("system");
            stockRecord.setRemark("修改秒杀商品信息");
            rocketMQTemplate.syncSend(Constants.SYNC_STOCK_OPERATION_TOPIC,stockRecord);
        }
    }

    private void checkSeckillGoods(Long id) {
        // 查询秒杀商品
        SeckillGoods sqlSeckillGoods = seckillGoodsMapper.selectById(id);
        if(    ( sqlSeckillGoods.getStartTime().getTime() < System.currentTimeMillis() &&
                sqlSeckillGoods.getEndTime().getTime() > System.currentTimeMillis() )  || // 正在秒杀
                ( sqlSeckillGoods.getStartTime().getTime() > System.currentTimeMillis() &&
                sqlSeckillGoods.getStartTime().getTime() - System.currentTimeMillis() < 5 * 60 * 1000 ) // 秒杀即将开始
        ) {
            throw new BusException(CodeEnum.SECKILL_GOODS_IN_SECKILLING);
        }
    }

    @Override
    public Page<SeckillGoods> findPage(int page, int size) {
        return seckillGoodsMapper.selectPage(Page.of(page, size), null);
    }
}
